package com.urban.pooling.controller.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.urban.pooling.domain.User;
import com.urban.pooling.dto.RouteDto;
import com.urban.pooling.dto.UserDto;
import com.urban.pooling.service.UserService;
import com.urban.pooling.util.AppUtil;
import com.urban.pooling.util.DomainUtil;

@Controller
@RequestMapping("/api/users")
public class UserApiController {
	@Autowired
	private UserService userService;

	private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

	/**
	 * Used in order to check the credentials of a user. If the request passes
	 * the security filters, return the authenticated user's details.
	 * 
	 * @return
	 */
	@RequestMapping(value = "authenticate", produces = { "application/json; charset=UTF-8" })
	public @ResponseBody
	String authenticate() {
		String username = AppUtil.getAuthenthicatedUsername();
		User user = userService.findByUsername(username);
		// TODO : clear sensitive data(use a dto or a helper method)
		return gson.toJson(new UserDto(user));
	}
	
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public @ResponseBody String registerUser(
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "lastName", required = true) String lastName ,
			@RequestParam(value = "email", required = true) String email,
			@RequestParam(value = "pass", required = true) String pass)
		{ //TODO:  RequestBody
		String msg = "Register failed! ";
		
		// validate
		User findByUsername = userService.findByUsername(username);
		User emailUnique = userService.isEmailUnique(email);
		
		if (findByUsername != null) {
			msg += "Username is allready allocated! ";
		}
		if (emailUnique != null) {
			msg += "Email is in use! ";
		}
		if (msg.length() > 20) {
			return msg;
		}
			UserDto user = new UserDto();
			user.setUsername(username);
			user.setFirstName(name);
			user.setLastName(lastName);
			user.setEmail(email);
			user.setPass(pass);
			String save = userService.save(user);
			return (save.equals("") ? "User successfully registered" : save);
	}
}
